<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;">

      <el-table-column label="序号" prop="id" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" align="center" width="120">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column label="排序" prop="sort" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="链接地址" prop="linkUrl" align="center" width="240">
        <template slot-scope="{row}">
          <span>{{ row.linkUrl }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" prop="imgUrl" align="center" width="180">
        <template slot-scope="{row}">
          <img :src="row.imgUrl" alt="" width="120" height="80">
        </template>
      </el-table-column>
      <el-table-column label="开始时间" prop="startTime" align="center" width="155">
        <template slot-scope="{row}">
          <span>{{ row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" prop="endTime" align="center" width="155">
        <template slot-scope="{row}">
          <span>{{ row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updateTime" align="center" width="155">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center" width="155">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px"
               style="width: 400px; margin-left:50px;">

        <el-form-item>
          <el-upload
            action="upload/image"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :accept="'image/*'">
            <img width="100%" :src="temp.imgUrl" alt="">
            <el-button
              class="filter-item"
              type="primary"
              size="medium">
              上传图片
            </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="标题">
          <el-input v-model="temp.title"/>
        </el-form-item>

        <el-form-item label="开始时间">
          <el-date-picker v-model="temp.startTime" type="datetime" placeholder="Please pick a date"/>
        </el-form-item>

        <el-form-item label="结束时间">
          <el-date-picker v-model="temp.endTime" type="datetime" placeholder="Please pick a date"/>
        </el-form-item>

        <el-form-item label="跳转链接">
          <el-input v-model="temp.linkUrl"/>
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model="temp.sort"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 1, maxRows: 4}" type="textarea"
                    placeholder="备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { fetchList, createBanner, deleteBanner } from '@/api/image'
  import { parseTime } from '@/utils'

  export default {
    name: 'index',
    components: {},
    data() {
      return {
        tableKey: 0,
        list: null,
        listLoading: true,
        downloadLoading: false,
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          id: undefined,
          remark: '',
          startTime: new Date(),
          endTime: new Date(),
          deleted: undefined,
          title: '',
          sort: 1,
          linkUrl: '',
          imgUrl: ''
        },
        textMap: {
          update: '编辑',
          create: '新增'
        },
        rules: {
          startTime: [{ type: 'date', required: true, message: 'startTime is required', trigger: 'change' }],
          endTime: [{ type: 'date', required: true, message: 'endTime is required', trigger: 'change' }],
          imgUrl: [{ required: true, message: 'imgUrl is required', trigger: 'blur' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        fetchList().then(response => {
          this.list = response.data

          setTimeout(() => {
            this.listLoading = false
          }, 500)
        })
      },

      handleUploadSuccess(response, file, fileList) {
        this.temp.imgUrl = response.data
      },

      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      createData() {
        this.$refs['dataForm'].validate((valid)=>{
          if (valid){
            this.temp.startTime = parseTime(this.temp.startTime)
            this.temp.endTime = parseTime(this.temp.endTime)
            createBanner(this.temp).then(response => {
              const res = response.data;
              console.log( response.data)
              if (res.code === 0) {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getList()
              }else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })
          }
        })
      },

      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.createData()
          }
        })
      },

      deleteData(param) {
        deleteBanner(param).then(response => {
          if (response.code === 0) {
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          }
        })
      },

      handleDelete(row) {
        const data = {
          id: row.id
        }

        this.$confirm('此操作将会删除这条记录，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteData(data)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },

      resetTemp() {
        this.temp = {
          id: undefined,
          remark: '',
          deleted: undefined,
          startTime: new Date(),
          endTime: new Date(),
          title: '',
          sort: 1,
          linkUrl: '',
          imgUrl: ''
        }
      }
    }
  }
</script>
